/**
 * Date：2017.05.13 星期六 下午
 * Function：用户控制操作和认证和创建令牌
 * E-mail：woaitianwen@qq.com
 * Author：zhouyulong
 */
var jwt = require('jsonwebtoken');

"use strict";

var mongoose = require('mongoose'),
    User = mongoose.model('Users');
//读取用户信息
exports.all_users = function(req, res) {
        User.find ({}, function(err, user) {
            if (err)
            res.send(err);
            res.json(user);
        });
};


//注册用户信息
exports.register = function(req, res) {

if (!req.body.username || !req.body.password) {
        res.json({success: false, msg: 'Please pass name and password.'});
} else {
    var new_user = new User({
        username: req.body.username,
        email: req.body.email,
        password: req.body.password
     });
     new_user.save(function(err,user) {
         if (err) {
             return res.json({success: false, msg: 'Username already exists.'});
         }
         res.json({success: true, msg: 'Successful created new user.'});
      });   
  }   

};

//获取用户ID
exports.userId = function(req, res) {
     User.findById(req.params.UserId, function(err, user) {
         if (err)
         res.send(err);
         res.json(user);
     });
};

//认证信息
exports.auth_token = function(req, res) {

    var data = {
        username: req.body.username,
        password: req.body.password
    };
     //查找用户
     User.findOne(data).lean().exec(function(err, user){
         if (err) {
             return res.json({success: false});
         }
         //检查用户是否匹配
         if (!user) {
             return res.status(404).json({success: false, msg: '验证失败：找不到用户名！'});
         } else if (user) {
                 //检查密码是否匹配
                 if (user.password != req.body.password) {
                     res.send({success: false, message: '验证失败：密码不符合！'});
                 } else {
                     //创建一个令牌
                      var token = jwt.sign(user, global.config.jwt_secret, {
                       expiresIn: 1440 //在1小时内过期
                   });
                  //将包含令牌的信息返回为JSON
                   res.json({
                       success: true, 
                       token: token
                    });
                     
                 }
         }
      
     });
};